<template>
  <div class="user-activities">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="header-content">
        <div class="logo">
          <h2>🏃‍♂️ 健身活动预约系统</h2>
        </div>
        <div class="nav">
          <el-button @click="$router.push('/user/home')" type="primary">首页</el-button>
          <el-button @click="$router.push('/user/bookings')">我的预约</el-button>
          <el-button @click="$router.push('/user/profile')">个人中心</el-button>
          <el-button @click="logout" type="danger">退出登录</el-button>
        </div>
      </div>
    </el-header>
    <!-- 主要内容 -->
    <el-main class="main-content">
      <!-- 搜索和筛选 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="活动名称">
            <el-input v-model="searchForm.title" placeholder="请输入活动名称" clearable />
          </el-form-item>
          <el-form-item label="活动地点">
            <el-input v-model="searchForm.location" placeholder="请输入活动地点" clearable />
          </el-form-item>
          <el-form-item label="价格范围">
            <el-input-number v-model="searchForm.minPrice" placeholder="最低价" :min="0" style="width: 120px" />
            <span style="margin: 0 10px">-</span>
            <el-input-number v-model="searchForm.maxPrice" placeholder="最高价" :min="0" style="width: 120px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 活动列表 -->
      <el-card class="activities-card">
        <template #header>
          <div class="card-header">
            <span>📋 活动列表</span>
            <div class="sort-options">
              <el-radio-group v-model="sortBy" @change="handleSort">
                <el-radio-button label="time">按时间</el-radio-button>
                <el-radio-button label="price">按价格</el-radio-button>
                <el-radio-button label="popularity">按热度</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8" v-for="activity in activities" :key="activity.id">
            <el-card class="activity-card" @click="viewActivity(activity.id)">
              <div class="activity-image">
                <img :src="getActivityImage(activity.title)" :alt="activity.title">
                <div class="activity-status" v-if="activity.status === 0">
                  <el-tag type="danger">已取消</el-tag>
                </div>
              </div>
              <div class="activity-info">
                <h3>{{ activity.title }}</h3>
                <p class="description">{{ activity.description }}</p>
                <p class="location">📍 {{ activity.location }}</p>
                <p class="time">🕐 {{ formatTime(activity.startTime) }}</p>
                <p class="price">💰 ¥{{ activity.price }}</p>
                <p class="participants">👥 {{ activity.currentParticipants }}/{{ activity.maxParticipants }}</p>
                <div class="action-buttons">
                  <el-button size="small" @click.stop="viewActivity(activity.id)">查看详情</el-button>
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click.stop="bookActivity(activity)"
                    :disabled="activity.status === 0 || activity.currentParticipants >= activity.maxParticipants"
                  >
                    {{ activity.currentParticipants >= activity.maxParticipants ? '已满员' : '立即预约' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[9, 18, 27, 36]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { activityApi } from '@/api'
import dayjs from 'dayjs'

const router = useRouter()

// 响应式数据
const activities = ref([])
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const sortBy = ref('time')

// 搜索表单
const searchForm = reactive({
  title: '',
  location: '',
  minPrice: null,
  maxPrice: null
})

// 方法
const loadActivities = async () => {
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined,
      location: searchForm.location || undefined
    }
    
    const res = await activityApi.getActivityList(params)
    activities.value = res.data.activities || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadActivities()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    location: '',
    minPrice: null,
    maxPrice: null
  })
  currentPage.value = 1
  loadActivities()
}

const handleSort = () => {
  // 根据排序方式重新加载数据
  loadActivities()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadActivities()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadActivities()
}

const viewActivity = (id) => {
  router.push(`/user/activity/${id}`)
}

const bookActivity = (activity) => {
  router.push(`/user/booking/create?activityId=${activity.id}`)
}

const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  ElMessage.success('退出登录成功')
  router.push('/login')
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const getActivityImage = (title) => {
  // 根据活动名称返回对应的图片
  const imageMap = {
    '瑜伽': '/images/yoga.jpg',
    '力量': '/images/strength.jpg',
    '有氧': '/images/cardio.jpg',
    '游泳': '/images/swimming.jpg',
    '拳击': '/images/boxing.jpg'
  }
  
  for (const [key, image] of Object.entries(imageMap)) {
    if (title.includes(key)) {
      return image
    }
  }
  return '/images/default.jpg'
}

// 生命周期
onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.user-activities {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid #e0e0e0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo h2 {
  margin: 0;
  color: #333;
}

.nav .el-button {
  margin-left: 10px;
}

.main-content {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.activities-card {
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sort-options {
  display: flex;
  align-items: center;
}

.activity-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s ease;
  border-radius: 10px;
  overflow: hidden;
}

.activity-card:hover {
  transform: translateY(-5px);
}

.activity-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.activity-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.activity-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.activity-info {
  padding: 15px;
}

.activity-info h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.description {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.activity-info p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.action-buttons {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style> 